package com.ruoyi.common.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.*;
/**
 *	工具类
 * @author liuz
 */
public class CommonUtil {

	public static String hiddenPhone(String phone) {
		if(phone.length()<=4){
			return "*****";
		}
		int head = 2;
		int tail = 2;
		if(phone.length() == 8 || phone.length() == 9) {
			head = 3;
			tail = 4;
		}else if(phone.length() > 9){
			head = 3;
			tail = 4;
		}
		return phone.replace(phone.substring(head, head + tail), "****");
	}
	
	public static String VIDEO_COVER="?x-oss-process=video/snapshot,ar_auto,t_10000,m_fast";

	public static String IMG_COVER = "?x-oss-process=image/resize,h_800,m_lfit";

	public static String IMG_COVER_Y = "?x-oss-process=image/resize,h_500,m_lfit";
	
	public static String IMG_COVER_PHOTO = "?x-oss-process=image/resize,h_1000,m_lfit";

	public static String IMG_SMALL_COVER = "?x-oss-process=image/resize,h_300,m_lfit";

	public static final String SPLIT_CODE = "_";

	public static String VIDEO_10 = "?x-oss-process=video/snapshot,ar_auto,t_10000,m_fast";
	public static String VIDEO_5 = "?x-oss-process=video/snapshot,ar_auto,t_5000,m_fast";

	public CommonUtil() {
	}

	public static String generateSplitCode() {
		byte[] bytes = new byte[]{5};
		String sendString = null;

		try {
			sendString = new String(bytes, "UTF-8");
			return sendString;
		} catch (UnsupportedEncodingException var3) {
			var3.printStackTrace();
			return "%";
		}
	}

	public static String md5(String input) {
		MessageDigest md = null;

		try {
			md = MessageDigest.getInstance("MD5");
		} catch (Exception var7) {
		}

		byte[] bs = md.digest(input.getBytes());
		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < bs.length; ++i) {
			int v = bs[i] & 255;
			if (v < 16) {
				sb.append(0);
			}

			sb.append(Integer.toHexString(v));
		}

		return sb.toString();
	}

	public static void responseJson(HttpServletResponse response, String content) {
		if (!isEmpty(content)) {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=UTF-8");

			try {
				PrintWriter out = response.getWriter();
				out.append(content);
			} catch (IOException var3) {
			}

		}
	}

	public static boolean isEmpty(Object[] arrays) {
		return arrays == null || arrays.length <= 0;
	}

	public static boolean isNotEmpty(Object[] arrays) {
		return !isEmpty(arrays);
	}


	public static boolean isEmpty(String str) {
		return str == null || "".equals(str);
	}


	public static boolean isEmpty(Number number) {
		return number == null;
	}

	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	public static String replaceHtml(String str) {
		if (str != null && !"".equals(str)) {
			str = str.replaceAll("<[^>]+>", "");
			str = str.replaceAll("&nbsp;", "");
			return str;
		} else {
			return str;
		}
	}

	public static String getLimitHtmlString(String str, int len) {
		if (str != null && !"".equals(str)) {
			str = getLimitString(str.replaceAll(" ", "").replaceAll("<[^>]+>", "").replaceAll("\r\n", "").replaceAll("&nbsp;", ""), len, true);
			return str;
		} else {
			return str;
		}
	}

	public static String getLimitString(String str, int len, boolean suffix) {
		String result = "";

		try {
			int counterOfDoubleByte = 0;
			byte[] b = str.getBytes("gbk");
			if (b.length <= len) {
				return str;
			}

			for (int i = 0; i < len; ++i) {
				if (b[i] < 0) {
					++counterOfDoubleByte;
				}
			}

			if (counterOfDoubleByte % 2 == 0) {
				result = new String(b, 0, len, "gbk");
			} else {
				result = new String(b, 0, len - 1, "gbk");
			}
		} catch (Exception var7) {
		}

		if (suffix && len > 0) {
			result = result + "...";
		}

		return result;
	}

	public static String html(String content) {
		if (content == null) {
			return "";
		} else {
			String html = content.replace("&#39;", "&apos;");
			html = content.replace("\"", "&quot;");
			html = content.replace("\t", "&nbsp;&nbsp;");
			html = content.replace("<", "&lt;");
			html = content.replace(">", "&gt;");
			return html;
		}
	}


	public static boolean isNumber(String str) {
		try {
			new BigDecimal(str);
			return true;
		} catch (Exception var2) {
			return false;
		}
	}

	public static String getIpAddr(HttpServletRequest request) {
		String fromSource = "User-Invoke-Real-Ip";
		String userInvoketRealIp = request.getHeader(fromSource);
		if (isNotEmpty(userInvoketRealIp)) {
			return userInvoketRealIp;
		} else {
			String xForwardedFor = null;
			if (isEmpty(userInvoketRealIp) || "unknown".equalsIgnoreCase(userInvoketRealIp)) {
				fromSource = "X-Forwarded-For";
				xForwardedFor = request.getHeader(fromSource);
				if (isNotEmpty(xForwardedFor)) {
					String[] ips = xForwardedFor.split(",");
					xForwardedFor = ips[0];
				}
			}

			if (isNotEmpty(xForwardedFor)) {
				return xForwardedFor;
			} else {
				String xRealIp = request.getHeader("X-Real-IP");
				if (isNotEmpty(xRealIp)) {
					return xRealIp;
				} else {
					String proxyClientIp = request.getHeader("Proxy-Client-IP");
					if (isNotEmpty(proxyClientIp)) {
						return proxyClientIp;
					} else {
						String wlProxyClientIp = request.getHeader("WL-Proxy-Client-IP");
						if (isNotEmpty(wlProxyClientIp)) {
							return wlProxyClientIp;
						} else {
							String remoteAddr = request.getRemoteAddr();
							return isNotEmpty(remoteAddr) ? remoteAddr : null;
						}
					}
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T clone(T source) throws IOException, ClassNotFoundException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(source);
		ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bais);
		return (T) ois.readObject();
	}

	public static <T extends Serializable, R extends Serializable> R copyByJSON(T t, Class<R> r) {
		return t == null ? null : (R) JSONObject.parseObject(JSONObject.toJSONString(t), r);
	}

	public static String processNickname(String nickname) {
		if (isEmpty(nickname)) {
			return nickname;
		} else {
			String result = nickname.replaceAll("[^0-9a-zA-Z一-龥.，,。？“”]+", "");
			return result;
		}
	}

	public static boolean isJson(String jsonStr) {
		try {
			JSONObject.parseObject(jsonStr);
			return true;
		} catch (Exception var2) {
			var2.printStackTrace();
			return false;
		}
	}

	public static boolean isNotJson(String jsonStr) {
		return !isJson(jsonStr);
	}



	public static <T> T transfer(Object a, Class<T> clazz) {
		try {
			String json = JSONObject.toJSONString(a);
			return JSONObject.parseObject(json, clazz);
		} catch (Throwable var3) {
			var3.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Set<String> getIpAddrSet(HttpServletRequest request) {
		JSONObject header = new JSONObject();
		Enumeration headerNames = request.getHeaderNames();

		String fromSource;
		while (headerNames.hasMoreElements()) {
			String name = (String) headerNames.nextElement();
			fromSource = request.getHeader(name);
			header.put(name, fromSource);
		}
		Set<String> ipSet = new HashSet();
		fromSource = "User-Invoke-Real-Ip";
		String userInvoketRealIp = request.getHeader(fromSource);
		if (isNotEmpty(userInvoketRealIp)) {
			ipSet.add(userInvoketRealIp);
		}

		String xForwardedFor = null;
		if (isEmpty(userInvoketRealIp) || "unknown".equalsIgnoreCase(userInvoketRealIp)) {
			fromSource = "X-Forwarded-For";
			xForwardedFor = request.getHeader(fromSource);
			if (isNotEmpty(xForwardedFor)) {
				String[] ips = xForwardedFor.split(",");
				xForwardedFor = ips[0];
			}
		}

		if (isNotEmpty(xForwardedFor)) {
			ipSet.add(xForwardedFor);
		}

		String xRealIp = request.getHeader("X-Real-IP");
		if (isNotEmpty(xRealIp)) {
			ipSet.add(xRealIp);
		}

		String proxyClientIp = request.getHeader("Proxy-Client-IP");
		if (isNotEmpty(proxyClientIp)) {
			ipSet.add(proxyClientIp);
		}

		String wlProxyClientIp = request.getHeader("WL-Proxy-Client-IP");
		if (isNotEmpty(wlProxyClientIp)) {
			ipSet.add(wlProxyClientIp);
		}

		String remoteAddr = request.getRemoteAddr();
		if (isNotEmpty(remoteAddr)) {
			ipSet.add(remoteAddr);
		}

		return ipSet;
	}

	public static String getClassessDir() {
		File file = new File(CommonUtil.class.getResource("/").getPath());
		return file.getAbsolutePath();
	}
	public static BigDecimal getBigDecimal( Object value ) {
		BigDecimal ret = null;
		if( value != null ) {
			if( value instanceof BigDecimal ) {
				ret = (BigDecimal) value;
			} else if( value instanceof String ) {
				ret = new BigDecimal( (String) value );
			} else if( value instanceof BigInteger ) {
				ret = new BigDecimal( (BigInteger) value );
			} else if( value instanceof Number ) {
				ret = new BigDecimal( ((Number)value).doubleValue() );
			} else {
				throw new ClassCastException("Not possible to coerce ["+value+"] from class "+value.getClass()+" into a BigDecimal.");
			}
		}
		return ret;
	}

	public static  int getAge(Date birthDay) {
		int age = 0;
		try {
			Calendar cal = Calendar.getInstance();
			if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
				throw new IllegalArgumentException(
						"The birthDay is before Now.It's unbelievable!");
			}
			int yearNow = cal.get(Calendar.YEAR);  //当前年份
			int monthNow = cal.get(Calendar.MONTH);  //当前月份
			int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
			cal.setTime(birthDay);
			int yearBirth = cal.get(Calendar.YEAR);
			int monthBirth = cal.get(Calendar.MONTH);
			int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
			age = yearNow - yearBirth;   //计算整岁数
			if (monthNow <= monthBirth) {
				if (monthNow == monthBirth) {
					if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
				}else{
					age--;//当前月份在生日之前，年龄减一1
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}        
		return age;
	}

	public static String getBirthday(int ageYear, int ageMonth, int ageDay) {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.YEAR, -ageYear);
		c.add(Calendar.MONTH, -ageMonth);
		c.add(Calendar.DAY_OF_MONTH, -ageDay);
		return String.format("%tF", c.getTime());
	}


	public static String splitAddress(String path){
		if (path.contains("http")){
			String[] substr = path.split("/");
			StringBuffer sb = new StringBuffer("");
			sb.append("/").append(substr[3]).append("/").append(substr[4]).append("/").append(substr[5]).append("/").append(substr[6]);
			return sb.toString();
		}else{
			return path;
		}
	}

	public static String splitAddressNew(String path){
		if (path.contains("http")){
			String[] substr = path.split("com");
			String result = path;
			if (substr.length == 2){
				result = substr[1];
			}else{
				String[] substr1 = path.split("cn");
				if(substr1.length == 2){
					result = substr1[1];
				}
			}
			return result;
		}else{
			return path;
		}
	}

	public static String getOssKey(String path){
		if (path.contains("http")){
			int index = path.indexOf("com/");
			String right = path.substring(index+4); 
			return right;
		}else{
			return "";
		}
	}

	public static String getScanImg(String path){
		if(path.contains("http")) {
			return path;
		}else {
			if("/".equals(path.substring(0, 1))){
				return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com"+path;
			}else{
				return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com/"+path;
			}
		}
	}

	public static String addAddress800(String path){
		if(StringUtils.isNotBlank(path)) {
			if(path.contains("http") && !path.contains("?")) {
				return path+IMG_COVER_Y;
			}else if(!path.contains("http") && !path.contains("?")) {
				return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com/"+path+IMG_COVER_Y;
			}
			return path;
		}else {
			return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com/user/headPic.png";
		} 
	}
	
	public static String addAddressPhoto(String path){
		if(StringUtils.isNotBlank(path)) {
			if(path.contains("http") && !path.contains("?")) {
				return path+IMG_COVER_PHOTO;
			}else if(!path.contains("http") && !path.contains("?")) {
				return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com/"+path+IMG_COVER_PHOTO;
			}
			return path;
		}else {
			return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com/user/headPic.png";
		} 
	}

	public static String addAddress(String path){
		if(StringUtils.isNotBlank(path)) {
			if(path.contains("http")) {
				return path;
			}
			return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com/"+path+IMG_COVER;
		}else {
			return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com/user/headPic.png";
		} 
	}

	public static String addAddressVideo(String path){
		if(StringUtils.isNotBlank(path)) {
			if(path.contains("http") || path.contains("https")) {
				return path;
			}
			return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com/"+path;
		}
		return "";
	}

	public static String addAddressCompress(String path){
		if(StringUtils.isNotBlank(path)) {
			if(path.contains("http")) {
				return path;
			}
			return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com/"+path+"?x-oss-process=image/resize,h_80,m_lfit";
		}else {
			return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com/user/headPic.png"+"?x-oss-process=image/resize,h_50,m_lfit";
		} 
	}

	public static String addAddressPopular(String path){
		if(StringUtils.isNotBlank(path)) {
			if(path.contains("http")) {
				return path;
			}
			return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com/"+path+"?x-oss-process=image/resize,h_300,m_lfit";
		}else {
			return "https://xinyangxiong.oss-cn-beijing.aliyuncs.com/user/headPic.png"+"?x-oss-process=image/resize,h_50,m_lfit";
		}
	}

	/**
	 * 	将微信号隐藏部分
	 * @param wechat
	 * @return
	 */
	public static String hiddenWechat(String wechat) {
		if(wechat.length()<=4){
			return "*****";
		}
		int head = 2;
		int tail = 2;
		if(wechat.length() == 8 || wechat.length() == 9) {
			head = 3;
			tail = 3;
		}else if(wechat.length() > 9){
			head = 4;
			tail = 4;
		}
		return wechat.replace(wechat.substring(head, head + tail), "***");
		// 中间要隐藏的位数
//        int body = wechat.length() - head - tail;
//		// 将字符串拆成三部分，并指定每部分长度的正则表达式
//        String regexVar = "(\\w{%d})(\\w{%d})(\\w{%d})";
//        String regex = String.format(regexVar, head, body, tail);
//        // 获取字符串中间要隐藏的部分，并替换成对应长度的*
//        String bodyPart = wechat.replaceAll(regex, "$2");
//        String bodyEncrypt = bodyPart.replaceAll("\\w", "*");
//        // 处理生成字符串replacement = "$1*****$3" 中间是对应长度的*号
//        String replacement = String.format("$1%s$3", bodyEncrypt);
//        return wechat.replaceAll(regex, replacement);
	}
	
	/**
	 * 	生成 环信 username
	 * @param length
	 * @return
	 */
	public static String getRandomUserName() {
		String english ="abcdefghijklmnopqrstuvwxyz";
		String hybrid = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<6;i++){
			int number= random.nextInt(36);
			if(i == 0) {
				sb.append(english.charAt(random.nextInt(26)));
				continue;
			}
			sb.append(hybrid.charAt(number));
		}
		return sb.toString();

	}


//	public static void main(String[] args) throws ParseException {
//		//System.out.println(splitAddress("https://xinyangxiong.oss-cn-beijing.aliyuncs.com/user/2020/08/15983666389013094.png"));
//		//		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
//		//		Date birthday = format.parse("19991209");
//
//	}
	public static void main(String[] args) {
		System.out.println(getRandomUserName());
	}
}